import { ParamsLack } from '../error/custom.error';
import { Context } from '@midwayjs/koa';
import { JwtService } from '@midwayjs/jwt';
import { UserService } from '../service/user.service';

const crypto = require('crypto');

// 判断某个数字是否在某个范围内, close为true时为闭区间
export const isBetween = (
  target: number,
  scope: [number, number],
  close: boolean = true
) => {
  const [min, max] = scope;
  if (close) {
    return target >= min && target <= max;
  } else {
    return target > min && target < max;
  }
};

// 检查必要参数是否齐全, 如果不是则抛出异常
export const checkEssentialParams = (...params) => {
  params.forEach(p => {
    if (p === undefined || p === '') {
      throw new ParamsLack();
    }
  });
};

// md5加密
export const md5 = (data: string) => {
  const hash = crypto.createHash('md5');
  return hash.update(data).digest('base64');
};

// 从token中获取用户信息
export const getUserFromToken = async (
  ctx: Context,
  jwtService: JwtService,
  userService: UserService
) => {
  const { username } = jwtService.decode(
    ctx.get('Authorization').split(' ')[1]
  ) as { username: string };
  return await userService.findUser(username);
};

// 同步定时器
export const timerSync = (ms: number) => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(ms);
    }, ms);
  });
};
